<template>
	<view class="content">
		<z-paging ref="pagingRef" v-model="mergedDataList" @query="queryDataList" :fixed="false" :page-size="10"
			:immediate="false">
			<!-- 遍历总数据列表，区分标题和数据项 -->
			<template v-for="(item, index) in mergedDataList" :key="index">
				<!-- 标题项渲染 -->
				<view class="title-text" v-if="item.type === 'title'">
					{{ item.text }}
				</view>

				<!-- 数据项渲染（根据来源和类型展示不同内容） -->
				<template v-if="item.type === 'data'">
					<!-- 兼职 PART_TIME_JOB -->
					<view class="item" :style="bgStyle" @click="itemClick(item.data)"
						v-if="item.data.browseType === 'PART_TIME_JOB'">
						<view class="uni-flex">
							<text class="text1">{{ item.data.partTimeResult.name }}</text>
							<view class="uni-flex uni-align-center xing_box"
								v-if="item.data.partTimeResult.isRecommended==='1'">
								<image :src="`${$ImgBaseUrl}part_time_xing.png`" mode="widthFix"
									class='part_time_xing' />
								<text class="text2">平台推荐</text>
							</view>
						</view>
						<text v-for="(label, i) in item.data.partTimeResult.labels" :key="i" class="project">
							{{ label }}
						</text>
						<view class="uni-flex uni-justify-between uni-align-center line3">
							<view>
								<text
									class="money">¥{{ item.data.partTimeResult.price === null ? '--' : item.data.partTimeResult.price }}</text>
								<!-- <text class="money_tip">元/小时</text> -->
							</view>
							<view class="sign-up" @click.stop="ContactEmployer(item.data)">联系雇主</view>
						</view>
					</view>

					<!-- 找活 JOB -->
					<view class="item" @click="itemClick(item.data)" v-if="item.data.browseType === 'JOB'">
						<view class="uni-flex uni-align-center top">
							<image :src="item.data.browseImg" class="photo" />
							<view class="uni-flex-column center">
								<text class="title">{{ item.data.busJobResult.name }}</text>
								<text class="distance">浏览时间：{{ item.data.browseTime }}</text>
							</view>
							<view class="uni-flex-column uni-align-center">
								<text
									:class="item.data.busJobResult.closeRate<=30?'num-red':item.data.busJobResult.closeRate<=60?'num-orange':'num'">{{item.data.busJobResult.closeRate}}%</text>
								<text class="text">结单率</text>
							</view>
						</view>
						<text v-for="(label, i) in item.data.busJobResult.labelNames" :key="i" class="project">
							{{ label }}
						</text>
						<view class="box">
							<text class="text1">服务内容：</text>
							<text
								class="text2">{{ item.data.busJobResult.content === null ? '--' : item.data.busJobResult.content }}</text>
						</view>
						<view class="uni-flex box">
							<view class="left">
								<text class="text1">发布时间：</text>
								<text class="text2">{{ item.data.busJobResult.createTime }}</text>
							</view>
							<text class="text3" v-if="item.data.busJobResult.hasOwnProperty('isBrowse')">浏览过</text>
						</view>
					</view>

					<!-- 优派 VIEW_SONIC -->
					<view class="item-VIEW_SONIC uni-flex uni-justify-between" @click="itemClick(item.data)"
						v-if="item.data.browseType === 'VIEW_SONIC'">
						<image class="left_img" referrerpolicy="no-referrer"
							:src="item.data.viewSonicResult.baseSmallImg" />
						<view class="uni-flex-item uni-flex uni-column uni-justify-between">
							<view class="title">{{ item.data.viewSonicResult.itemName }}</view>
							<view class="desc">{{ item.data.viewSonicResult.remark }}</view>
							<view class="uni-flex uni-justify-between uni-align-center">
								<view>
									<text class="price1">¥</text>
									<text
										class="price2">{{ item.data.viewSonicResult.paramMinPrice }}-{{ item.data.viewSonicResult.paramMaxPrice }}</text>
									<text class="text3">/{{ item.data.viewSonicResult.paramPriceUnit }}</text>
								</view>
								<uni-icons type="right" size="12" color="#999999"></uni-icons>
							</view>
						</view>
					</view>

					<!-- 找人 USER -->
					<view class="item" @click="itemClick(item.data)" v-if="item.data.browseType === 'USER'">
						<view class="uni-flex uni-align-center top">
							<view class="photo-box">
								<image :src="item.data.userResult.avatar" class="photo" />
								<text class="online">{{ item.data.userResult.isOnLine === true ? '在线' : '离线' }}</text>
							</view>
							<view class="uni-flex-column" style="flex: 1">
								<view class="uni-flex uni-align-center uni-justify-between box1">
									<view class="uni-flex">
										<text class="title">{{ item.data.userResult.name }}</text>
										<view class="real-name">
											<image :src="`${$ImgBaseUrl}findpeople_realname.png`" mode="widthFix"
												class="people-icon" />
											<text
												class="text1">{{ item.data.userResult.isRealName === true ? '已实名' : '未实名' }}</text>
										</view>
										<view class="sign-contract">
											<image :src="`${$ImgBaseUrl}findpeople_sign.png`" mode="widthFix"
												class="people-icon" />
											<text
												class="text1">{{ item.data.userResult.isSignService === true ? '已签约' : '未签约' }}</text>
										</view>
									</view>
									<view class="distance-box">
										<image :src="`${$ImgBaseUrl}detail_location.png`" mode="widthFix"
											class="people-icon" />
										<text class="text1">{{ item.data.userResult.distance }}km</text>
									</view>
								</view>
								<view class="box2">
									<text class="text1">
										{{ item.data.userResult.sex === "0" ? '男' : item.data.userResult.sex === "1" ? '女' : '未知' }}
										| {{ item.data.age }}岁 | 服务
									</text>
									<text class="text2">{{ item.data.userResult.closeCount }}</text>
									<text class="text1">单 | 评价</text>
									<text class="text2">{{ item.data.userResult.comEvaluation }}</text>
									<text class="text1">分</text>
								</view>
							</view>
						</view>
						<view class="uni-flex box3">
							<text class="text1">可接业务: </text>
							<view class="con">
								<template v-if="item.data.services && item.data.services.length > 0">
									<view v-for="(s, i) in item.data.services" :key="i" class="text2">{{ s }}</view>
								</template>
								<template v-else>
									<view class="empty-text">暂无</view>
								</template>
							</view>
						</view>
						<view class="uni-flex box3">
							<text class="text1">擅长服务: </text>
							<view class="con">
								<template v-if="item.data.goodServices && item.data.goodServices.length > 0">
									<view v-for="(g, i) in item.data.goodServices" :key="i" class="project">{{ g }}
									</view>
								</template>
								<template v-else>
									<view class="empty-text">暂无</view>
								</template>
							</view>
						</view>
						<view class="footer">
							<view class="btn">试一下</view>
						</view>
					</view>

					<!-- 附近 -->
					<!-- <view class="content" v-if="item.data.browseType === 'NEARBY_MERCHANT'"> -->
					<!-- <view class="item-list" > -->
					<view class="item-near" v-if="item.data.browseType === 'NEARBY_MERCHANT'"
						@click="itemClick(item.data)">
						<view class="shop-top">
							<image class="shop-photo" :src="item?.data?.merchant?.merImagesList[0]" mode="widthFix" />
							<view class="distance-tag">
								<text class="distance-text">{{ item?.data?.merchant?.distance }}km</text>
							</view>
						</view>
						<view class="shop-name">
							<text class="name-text">{{ item?.data?.merchant?.merName }}</text>
						</view>
					</view>
					<!-- </view> -->
					<!-- </view> -->
				</template>
			</template>

			<template #empty>
				<view class="empty-container">暂无数据</view>
			</template>
		</z-paging>
		<CallDialog :showDialog="showCallDialog" :phoneNumber="phoneNumber" @close="showCallDialog = false">
		</CallDialog>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
	} from "vue";
	import {
		browseReceiveList,
		recentlyList
	} from '@/api/browsinghistory.js';
	import {
		getUserEncryption
	} from '@/api/findPeople.js'
	import {
		onShow
	} from '@dcloudio/uni-app';
	import {
		getLatitude,
		getLongitude
	} from "@/common/util.js";
	import {
		ImgBaseUrl
	} from "@/utils/domain.js";
	import CallDialog from '@/components/CallDialog.vue'

	const pagingRef = ref(null);
	const threeDayData = ref([]); // 单独存储三日内数据
	const historyData = ref([]); // 单独存储历史数据
	const threeDayLoaded = ref(false);
	const showCallDialog = ref(false)
	const phoneNumber = ref(''); // 初始默认号码
	const bgStyle = computed(() => ({
		backgroundImage: `url(${ImgBaseUrl}part_time_item_bg.png)`,
	}));


	// 合并后的数据（计算属性）
	const mergedDataList = computed(() => {
		const result = [];

		// 添加三日内数据（如果有）
		if (threeDayData.value.length > 0) {
			result.push({
				type: 'title',
				text: '三日内访问'
			});
			result.push(...threeDayData.value);
		}

		// 添加历史数据（如果有）
		if (historyData.value.length > 0) {
			// 只有当有三日内数据时才添加历史记录标题
			if (threeDayData.value.length > 0) {
				result.push({
					type: 'title',
					text: '历史记录'
				});
			}
			result.push(...historyData.value);
		}

		return result;
	});

	// 暴露reload方法
	const reload = () => {
		threeDayData.value = [];
		historyData.value = [];
		threeDayLoaded.value = false;
		pagingRef.value?.reload();
	};
	// 暴露给模板
	defineExpose({
		reload
	});

	// 统一数据查询方法
	const queryDataList = async (pageNum, pageSize) => {
		try {
			// 第一步：加载三日内数据（仅首次）
			if (!threeDayLoaded.value) {
				const res = await recentlyList({
					browseType: 1,
					longitude: getLongitude(),
					latitude: getLatitude(),
					pageNum: 1,
					pageSize: 100,
				});

				if (res?.code === 200) {
					const list = res.data?.list || res.data || [];
					threeDayData.value = list.map(item => ({
						type: 'data',
						data: item
					}));
				}
				threeDayLoaded.value = true;
			}

			// 第二步：加载历史数据
			const res = await browseReceiveList({
				browseType: 1,
				longitude: getLongitude(),
				latitude: getLatitude(),
				pageNum,
				pageSize,
			});

			if (res?.code === 200) {
				let list = [];
				let total = 0;

				if (res.rows) {
					list = res.rows;
					total = res.total;
				} else if (res.data?.rows) {
					list = res.data.rows;
					total = res.data.total;
				}

				const formattedList = list.map(item => ({
					type: 'data',
					data: item
				}));

				if (pageNum === 1) {
					historyData.value = formattedList;
				} else {
					historyData.value.push(...formattedList);
				}

				const hasMore = pageNum * pageSize < total;
				pagingRef.value.complete(formattedList, !hasMore);
			} else {
				pagingRef.value.complete([], true);
			}
		} catch (error) {
			console.error('数据加载失败:', error);
			pagingRef.value.complete(false);
		}
	};
	// 点击项目跳转
	const itemClick = (item) => {
		console.log('点击项目:', item);
		if (item.browseType === 'PART_TIME_JOB') {
			uni.navigateTo({
				url: `/pages/tabBars/findPartTimeJob/partTimeDetail?id=${item.id}`
			});
		} else if (item.browseType === 'JOB') {
			uni.navigateTo({
				url: '/pages/tabBars/findJob/jobDetail?jobId=' + item.id
			});
		} else if (item.browseType === 'VIEW_SONIC') {
			uni.navigateTo({
				url: "/pages/viewSonic/viewSonicDetail?id=" + item.id
			});
		} else if (item.browseType === 'USER') {
			uni.navigateTo({
				url: `/pages/tabBars/findPeople/peopleDetail?jobId=${item.userResult.userId}`
			});
		} else if (item.browseType === 'NEARBY_MERCHANT') {
			uni.navigateTo({
				url: `/pages/nearby/nearDetails?item=${encodeURIComponent(JSON.stringify(item))}`
			});
		}
	};
	// 联系雇主
	const ContactEmployer = async (item) => {
		console.log('item', item);
		const user_info = uni.getStorageSync('user_info');
		if (user_info) {
			const id = JSON.parse(user_info).id
			if (id === item.partTimeResult.userId) {
				uni.showToast({
					title: '不能联系自己发布的兼职',
					icon: 'none'
				})
			} else {
				showCallDialog.value = true
				try {
					const res = await getUserEncryption(item.partTimeResult.userId);
					console.log('获取加密号码接口返回', res);
					if (res.code === 200) {
						phoneNumber.value = res.data
					}
					// 假设接口返回的加密号码字段是 encryptionPhone，根据实际接口调整

				} catch (err) {
					console.error('获取加密号码失败', err);
				}
			}
		}

	}
	// 页面显示时重新加载数据
	onShow(() => {
		reload();
	});
</script>

<style lang="scss" scoped>
	.content {
		height: calc(100vh - 240rpx);
		padding: 0 20rpx 20rpx;
		background-color: #f5f5f5; // 添加背景色区分区域
	}

	// 标题样式
	.title-text {
		font-weight: 400;
		font-size: 28rpx;
		color: #666666;
		margin: 30rpx 0 20rpx 0;
		padding-left: 4rpx; // 与原样式对齐
	}

	// 数据项通用样式（保持原样式不变）
	.item {
		background-size: 100% 100%;
		background-repeat: no-repeat;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		background-color: #fff;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

		.uni-flex {
			display: flex;
			align-items: center;
		}

		.text1 {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.xing_box {
			.part_time_xing {
				width: 47rpx !important;
				height: 47rpx !important;
				margin-right: 8rpx !important;
			}

			.text2 {
				font-size: 24rpx;
				color: #FF9D00;
			}
		}

		.project {
			display: inline-block;
			padding: 6rpx 16rpx;
			background: #F8F8F8;
			border-radius: 8rpx;
			font-size: 24rpx;
			color: #666;
			margin-right: 12rpx;
			margin-top: 16rpx;
		}

		.line3 {
			margin-top: 30rpx;

			.money {
				font-size: 36rpx;
				color: #FF5A1F;
				font-weight: bold;
			}

			.money_tip {
				font-size: 24rpx;
				color: #999;
				margin-left: 8rpx;
			}

			.sign-up {
				padding: 10rpx 30rpx;
				background: linear-gradient(90deg, #FF7A45, #FF5A1F);
				border-radius: 40rpx;
				color: #fff;
				font-size: 28rpx;
			}
		}

		.top {
			.photo {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				margin-right: 20rpx;
			}

			.center {
				flex: 1;

				.title {
					font-size: 28rpx;
					font-weight: 500;
					color: #333;
				}

				.distance {
					font-size: 24rpx;
					color: #999;
					margin-top: 8rpx;
				}
			}

			.num {
				font-size: 36rpx;
				font-weight: bold;
				color: #6bc98d;
				font-weight: 500;
				margin-bottom: 10rpx;
			}

			.num-red {
				font-weight: 500;
				font-size: 36rpx;
				color: #FF6A47;
			}

			.num-orange {
				font-weight: 500;
				font-size: 36rpx;
				color: #FEB310;
			}

			.text {
				font-size: 24rpx;
				color: #999;
				margin-top: 4rpx;
			}
		}

		.box {
			margin-top: 20rpx;
			font-size: 26rpx;

			.text1 {
				color: #999;
				font-size: 26rpx;
				font-weight: normal;
			}

			.text2 {
				color: #333;
				display: -webkit-box;
				/* 弹性盒模型，用于多行文本溢出 */
				-webkit-box-orient: vertical;
				/* 垂直排列 */
				-webkit-line-clamp: 4;
				/* 限制显示3行 */
				overflow: hidden;
				/* 溢出内容隐藏 */
				text-overflow: ellipsis;
				/* 溢出部分显示省略号 */
				word-break: break-all;
			}

			.left {
				flex: 1;
			}

			.text3 {
				color: #2F80ED;
			}
		}
	}

	// 优派样式
	.item-VIEW_SONIC {
		background: #ffffff;
		box-shadow: 0px 5rpx 20rpx 0px #e2e8f0;
		border-radius: 20rpx;
		padding: 24rpx 23rpx;
		margin-bottom: 20rpx;

		.left_img {
			width: 203rpx;
			height: 203rpx;
			margin-right: 21rpx;
			border-radius: 20rpx;
		}

		.title {
			font-weight: 500;
			font-size: 32rpx;
			color: #333333;
			line-height: 45rpx;
		}

		.desc {
			font-weight: 400;
			font-size: 24rpx;
			color: #999999;
			line-height: 33rpx;
			margin-top: 15rpx;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		.price1 {
			font-size: 20rpx;
			color: #ff6a47;
		}

		.price2 {
			font-size: 32rpx;
			color: #ff6a47;
		}

		.text3 {
			font-weight: 400;
			font-size: 20rpx;
			color: #999999;
			line-height: 28rpx;
		}
	}

	// 找人样式补充
	.item {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx 20rpx;
		// margin: 26rpx 24rpx 0;


		.top {
			padding-bottom: 18rpx;
			border-bottom: 1rpx solid #ededed;

			.photo-box {
				position: relative;

				.photo {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
					margin-right: 24rpx;
				}

				.online {
					position: absolute;
					bottom: 0;
					left: 10rpx;
					color: white;
					background: #6bc98d;
					border-radius: 17rpx;
					padding: 5rpx 0;
					font-weight: 500;
					width: 80rpx;
					text-align: center;
					font-size: 22rpx;
				}
			}

			.box1 {
				margin-bottom: 9rpx;

				.title {
					font-size: 32rpx;
					font-weight: 500;
					color: #333333;
					margin-right: 8rpx;
				}

				.real-name {
					background: #ffeae6;
					border-radius: 17px;
					border: 1px solid #ff6a47;
					// padding: 4rpx 18rpx;
					// margin-left: 8rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					width: 116rpx;
					height: 34rpx;

					image {
						width: 20rpx;
						height: 20rpx;
						margin-right: 8rpx;
					}

					.text1 {
						font-weight: 500;
						font-size: 22rpx;
						color: #ff6a47;
					}
				}

				.sign-contract {
					background: #e5f0ff;
					border-radius: 17px;
					border: 1px solid #2f80ed;
					// padding: 4rpx 18rpx;
					margin-left: 8rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					width: 116rpx;
					height: 34rpx;

					image {
						width: 20rpx;
						height: 20rpx;
						margin-right: 8rpx;
					}

					.text1 {
						font-weight: 500;
						font-size: 22rpx;
						color: #2f80ed;
					}
				}

				.distance-box {
					display: flex;
					align-items: center;

					.people-icon {
						width: 20rpx;
						height: 20rpx;
						margin-right: 8rpx;
					}

					.text1 {
						font-weight: 400;
						font-size: 24rpx;
						color: #666666;
					}
				}
			}

			.box2 {
				.text1 {
					font-size: 24rpx;
					color: #999999;
				}

				.text2 {
					font-size: 24rpx;
					color: #2f80ed;
				}
			}
		}

		.box3 {
			align-items: flex-start;
			/* 顶部对齐 */
			width: 100%;
			margin-top: 16rpx;

			.text1 {
				font-size: 28rpx;
				color: #666666;
				flex-shrink: 0;
				/* 防止标签被压缩 */
			}

			.con {
				flex: 1;
				display: flex;
				flex-wrap: wrap;
				/* 关键属性：允许换行 */
				gap: 10rpx;
				/* 项目间距 */
				margin-left: 20rpx;

				.empty-text {
					font-size: 28rpx;
					color: #666666;
					flex-shrink: 0;
					/* 防止标签被压缩 */
				}

				.text2 {
					font-size: 28rpx;
					color: #333333;
				}

				.project {
					color: #2f80ed;
					font-size: 24rpx;
					font-weight: 500;
					background: #e5f0ff;
					padding: 6rpx 10rpx;
					margin-right: 14rpx;
					border-radius: 4rpx;
					white-space: nowrap;
					/* 单行显示 */
				}
			}
		}

		.footer {
			display: flex;
			justify-content: flex-end;
			/* 将子元素推到右侧 */
			width: 100%;
			margin-top: 20rpx;

			.btn {
				font-weight: 500;
				font-size: 30rpx;
				color: #ffffff;
				width: 163rpx;
				height: 68rpx;
				line-height: 68rpx;
				background: #2f80ed;
				border-radius: 34rpx;
				text-align: center;
			}
		}
	}

	// 附近
	// .content {
	// 	padding: 20rpx;


	// }
	// .item-list {
	// 	display: flex;
	// 	flex-wrap: wrap;
	// 	justify-content: space-between;
	// 	// padding: 10rpx;
	// 	box-sizing: border-box;

	.item-near {
		// width: calc(50% - 20rpx);
		margin-bottom: 20rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		box-sizing: border-box;
		overflow: hidden;

		.shop-top {
			position: relative;
			width: 100%;

			.shop-photo {
				width: 100%;
				height: 200rpx;
				object-fit: cover;
				display: block;
				border-top-right-radius: 20rpx;
				border-top-left-radius: 20rpx;
			}

			.distance-tag {
				position: absolute;
				top: 10rpx;
				right: 10rpx;
				background: rgba(0, 0, 0, 0.5);
				color: #fff;
				font-size: 24rpx;
				padding: 5rpx 15rpx;
				border-radius: 24rpx;
				z-index: 10;
				font-weight: 400;
			}
		}

		.shop-name {
			padding: 30rpx;

			.name-text {
				font-size: 30rpx;
				color: #333;
				font-weight: 500;
				width: 100%;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}
	}

	// }

	// 空数据样式
	.empty-container {
		min-height: 120rpx;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>